package com.example.echoewish.ui.home_activity;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.echoewish.R;
import com.example.echoewish.pojo.Comment;
import com.example.echoewish.pojo.DetailPost;
import com.example.echoewish.econstant.Constant;
import com.example.echoewish.econstant.UserInfo;
import com.example.echoewish.ui.EchoWishCompatActivity;
import com.example.echoewish.ui.my_activity.user_info_activity.UserInfoShowActivity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

public class PostDetailActivity extends EchoWishCompatActivity {
    private final static  int GET_POST_DETAIL_SUCCESS=3;
    private final static  int GET_POST_DETAIL_FAIL=4;
    private final static int GET_USER_INFO_SUCCESS=5;
    private final static int GET_COMMENT_INFO_SUCCESS=7;
    private final static int GET_COLLECT_INFO_SUCCESS=8;
    private final static int COLLECT_SUCCESS=9;
    private final static int COLLECT_FAIL=10;

    private TextView titleTextView;
    private CircleImageView headImageView;
    private TextView nameTextView;
    private TextView dateTextView;
    private TextView contentTextView;
    private ImageView postImageView;
    private LinearLayout rewardLinearLayout;
    private TextView rewardTextView;
    private EditText commentEditText;
    private Button commentButton;
    private TextView visitsTextView;
    private ImageView collectionsImageView;

    private ListView commentListView;
    private CommentAdapter commentAdapter;
    private int sum=0;

    private PostDetailViewModel postDetailViewModel;

    private Handler postDetailHandler=new Handler()
    {
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what)
            {
                case Constant.HTTPS_GET_CALLBACK_FAIL_MESSAGE:
                    Toast.makeText(PostDetailActivity.this,"网络连接错误",Toast.LENGTH_SHORT).show();
                    break;
                case  Constant.HTTPS_GET_CALLBACK_SUCCESS_MESSAGE:
                    if(msg.arg1==GET_POST_DETAIL_SUCCESS) {
                        postDetailViewModel.queryIsCollect();
                        initDetailMessage();
                        postDetailViewModel.getComment();
                    }
                    else if(msg.arg1==GET_COMMENT_INFO_SUCCESS)
                    {

                        Log.d(Constant.NETWORK_TAG, "更改评论成功");
                        commentAdapter.clear();
                        commentAdapter.addAll(postDetailViewModel.commentMutableLiveData.getValue());

                        //改变listview大小
                        sum=0;
                        int listViewWidth = ((Activity)PostDetailActivity.this).getWindowManager().getDefaultDisplay().getWidth();
                        int widthSpec = View.MeasureSpec.makeMeasureSpec(listViewWidth, View.MeasureSpec.AT_MOST);
                        System.out.println(100);
                        for(int i=0;i<commentAdapter.getCount();i++){
                            View view = commentAdapter.getView(i, null, commentListView);
                            view.measure(widthSpec, 0);
                            sum += view.getMeasuredHeight();
                        }

                        ViewGroup.LayoutParams  lp = commentListView.getLayoutParams();
                        lp.height=sum;
                        commentListView.setLayoutParams(lp);
                        commentAdapter.notifyDataSetChanged();


                    }
                    else
                    {
                        postDetailViewModel.commentMutableLiveData.getValue().add(postDetailViewModel.publishCommentMutableLiveData.getValue());
                        commentAdapter.add(postDetailViewModel.publishCommentMutableLiveData.getValue());
                        int listViewWidth = ((Activity)PostDetailActivity.this).getWindowManager().getDefaultDisplay().getWidth();
                        int widthSpec = View.MeasureSpec.makeMeasureSpec(listViewWidth, View.MeasureSpec.AT_MOST);
                        View view = commentAdapter.getView(commentAdapter.getCount()-1, null, commentListView);
                        view.measure(widthSpec, 0);
                        sum+=view.getMeasuredHeight();

                        ViewGroup.LayoutParams  lp = commentListView.getLayoutParams();
                        lp.height=sum;
                        commentListView.setLayoutParams(lp);
                        commentAdapter.notifyDataSetChanged();
                        Toast.makeText(PostDetailActivity.this,"发布成功",Toast.LENGTH_SHORT).show();
                    }
                    break;
                case GET_COLLECT_INFO_SUCCESS:
                    if(postDetailViewModel.isCollectMutableLiveData.getValue())
                    Glide.with(PostDetailActivity.this).load(R.drawable.collection_after).into(collectionsImageView);
                    else
                        Glide.with(PostDetailActivity.this).load(R.drawable.collection_before).into(collectionsImageView);
                    break;
                case COLLECT_SUCCESS:
                        postDetailViewModel.isCollectMutableLiveData.postValue(!postDetailViewModel.isCollectMutableLiveData.getValue());
                    Toast.makeText(PostDetailActivity.this,"操作成功",Toast.LENGTH_SHORT).show();
                    break;
                case COLLECT_FAIL:
                    Toast.makeText(PostDetailActivity.this,"网络异常",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        postDetailViewModel.postIdMutableLiveData.setValue(getIntent().getIntExtra("postId",-1));
    }

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_post_detail);
    }


    public void initView()
    {

        titleTextView=findViewById(R.id.post_detail_title_textview);
        headImageView=findViewById(R.id.post_detail_head_imageview);
        nameTextView=findViewById(R.id.post_detail_name_textview);
        dateTextView=findViewById(R.id.post_detail_time_textview);
        contentTextView=findViewById(R.id.post_detail_content_textview);
        postImageView=findViewById(R.id.post_detail_imageview);
        rewardTextView=findViewById(R.id.post_detail_reward_textview);
        commentListView=findViewById(R.id.post_detail_command_listview);
        commentButton=findViewById(R.id.post_detail_comment_button);
        commentEditText=findViewById(R.id.post_detail_comment_textview);
        rewardLinearLayout=findViewById(R.id.publish_reward_linear_layout);
        visitsTextView=findViewById(R.id.post_detail_visits_textview);
        collectionsImageView=findViewById(R.id.post_detail_collections_imagebutton);


        //评论列表初始化
        commentAdapter=new CommentAdapter(this,R.layout.comment_item,new LinkedList<>());
        commentListView.setAdapter(commentAdapter);

        //响应
        commentButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(commentEditText.getText().toString().equals(""))
                {
                    Toast.makeText(PostDetailActivity.this,"评论内容不能为空",Toast.LENGTH_SHORT).show();
                    return;
                }
                publishNewComment(commentEditText.getText().toString());
            }
        });

        headImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(UserInfo.getInstance().IsLogin)
                {
                    UserInfoShowActivity.activityStart(PostDetailActivity.this,postDetailViewModel.detailPostMutableLiveData.getValue().userId);
                }
                else
                    Toast.makeText(PostDetailActivity.this,"未登录，不能查看",Toast.LENGTH_SHORT).show();
            }
        });

        collectionsImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(UserInfo.getInstance().IsLogin)
                {
                    postDetailViewModel.collectOrCancelPost();
                }
                else
                    Toast.makeText(PostDetailActivity.this,"请先登录",Toast.LENGTH_SHORT).show();
            }
        });
    }


    private void initDetailMessage()
    {

        //这两个必定存在
        titleTextView.setText(postDetailViewModel.detailPostMutableLiveData.getValue().title);
        contentTextView.setText(postDetailViewModel.detailPostMutableLiveData.getValue().content);
        dateTextView.setText(postDetailViewModel.detailPostMutableLiveData.getValue().time);
        nameTextView.setText(postDetailViewModel.detailPostMutableLiveData.getValue().name);
        visitsTextView.setText("访问量"+postDetailViewModel.detailPostMutableLiveData.getValue().visits);


        System.out.println(postDetailViewModel.detailPostMutableLiveData.getValue().name);

        String reward=postDetailViewModel.detailPostMutableLiveData.getValue().reward;
        String postImage=postDetailViewModel.detailPostMutableLiveData.getValue().postImage;
        String headImage=postDetailViewModel.detailPostMutableLiveData.getValue().headImage;

        if(reward!=null&&!reward.equals(""))
        {
            //只有控件layout中设置visibility时 这个才起效
            rewardLinearLayout.setVisibility(View.VISIBLE);
//            findViewById(R.id.post_detail_reward_title_textview).setVisibility(View.VISIBLE);
//            rewardTextView.setVisibility(View.VISIBLE);
            rewardTextView.setText(reward);
        }

        if(postImage!=null&&!postImage.equals(""))
        {
            postImageView.setVisibility(View.VISIBLE);
            Glide.with(this).load(Constant.POST_IMAGE_URL+postImage).into(postImageView);
        }

        if(headImage!=null&&!headImage.equals(""))
        {
            Glide.with(this).load(Constant.HEAD_IMAGE_URL+headImage).into(headImageView);
        }

//        Glide.with(this).load(R.drawable.collection_after).into(collectionsImageView);


    }

    @Override
    public void initViewModel() {
        postDetailViewModel=new ViewModelProvider(this,new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(PostDetailViewModel.class);
    }

    @Override
    public void observeLiveData() {
        postDetailViewModel.postIdMutableLiveData.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                if(integer!=-1)
                postDetailViewModel.getDetailPost();
            }
        });

        postDetailViewModel.detailPostMutableLiveData.observe(this, new Observer<DetailPost>() {
            @Override
            public void onChanged(DetailPost detailPost) {
                Message message=new Message();
                message.what=Constant.HTTPS_GET_CALLBACK_SUCCESS_MESSAGE;
                if(detailPost==null)
                    message.arg1=GET_POST_DETAIL_FAIL;
                else
                    message.arg1= GET_POST_DETAIL_SUCCESS;
                postDetailHandler.sendMessage(message);
            }
        });

        postDetailViewModel.publishCommentMutableLiveData.observe(this, new Observer<Comment>() {
            @Override
            public void onChanged(Comment comment) {
                postDetailViewModel.publishComment();
            }
        });

        postDetailViewModel.commentMutableLiveData.observe(this, new Observer<List<Comment>>() {
            @Override
            public void onChanged(List<Comment> comments) {
                if(comments!=null)
                {
                    Message message=new Message();
                    message.what=Constant.HTTPS_GET_CALLBACK_SUCCESS_MESSAGE;
                    message.arg1=GET_COMMENT_INFO_SUCCESS;
                    postDetailHandler.sendMessage(message);
                }
            }
        });

        postDetailViewModel.responseMutableLiveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Message message=new Message();
                if(s.equals(Constant.HTTPS_GET_CALLBACK_SUCCESS))
                {
                    message.what=Constant.HTTPS_GET_CALLBACK_SUCCESS_MESSAGE;
                    postDetailHandler.sendMessage(message);
                }
                else
                {
                    message.what=Constant.HTTPS_GET_CALLBACK_FAIL_MESSAGE;
                    postDetailHandler.sendMessage(message);
                }
            }
        });

        postDetailViewModel.isCollectMutableLiveData.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if(aBoolean)
                {
                    Message message=new Message();
                    message.what=GET_COLLECT_INFO_SUCCESS;
                    postDetailHandler.sendMessage(message);
                }
            }
        });


        postDetailViewModel.collectResponseMutableLiveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Message message=new Message();
                if(s.equals(Constant.HTTPS_GET_CALLBACK_SUCCESS))
                {
                    message.what=COLLECT_SUCCESS;
                    postDetailHandler.sendMessage(message);
                }
                else
                {
                    message.what=COLLECT_FAIL;
                    postDetailHandler.sendMessage(message);
                }
            }
        });
    }

    public void publishNewComment(String content)
    {
        Comment myPublishComment=new Comment();
        if(!UserInfo.getInstance().IsLogin)
        {
            Toast.makeText(this,"未登录，不能评论",Toast.LENGTH_SHORT).show();
            return;
        }
        myPublishComment.postId=postDetailViewModel.postIdMutableLiveData.getValue();
        myPublishComment.userId= UserInfo.getInstance().UserId;
        myPublishComment.content=content;
        myPublishComment.imageName=UserInfo.getInstance().headImage;
        myPublishComment.name=UserInfo.getInstance().name;
        Date date=new Date();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat(Constant.FILE_NAME_OR_COMMENT_FORMAT);
        String nowTime=simpleDateFormat.format(date);
        myPublishComment.time=nowTime;
        postDetailViewModel.publishCommentMutableLiveData.setValue(myPublishComment);
    }
}